package com.dhl.fin.api.timer;

import com.dhl.fin.api.common.annotation.SchedulePlan;
import com.dhl.fin.api.common.util.DateUtil;
import com.dhl.fin.api.common.util.FilesUtil;
import com.dhl.fin.api.common.util.StringUtil;
import com.dhl.fin.api.common.util.excel.ExcelUtil;
import com.dhl.fin.api.domain.Stock;
import com.dhl.fin.api.service.StockServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author CuiJianbo
 * @since 2023/9/26
 */
@Slf4j
@Service
public class Jobs {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private StockServiceImpl stockService;


    @SchedulePlan(name = "自动导入股市快照", cron = "3 48 * * * ?", env = "uat")
    public void importStockData() {
        String filePath = "D:\\Beck Work Space\\SynologyDrive\\Personal\\stock\\stock excel\\股市快照\\ss";
        String finishedFilePath = "D:\\Beck Work Space\\SynologyDrive\\Personal\\stock\\stock excel\\已经导入到数据库的快照\\";

        List<File> files = FilesUtil.getFiles(filePath);
        log.info("文件数量：" + files.size());
        for (File file : files) {
            try {
                String date = file.getName().split("\\.")[0].trim();
                jdbcTemplate.execute("delete from t_stock where date='" + date + "'");

                List<Stock> stocks = ExcelUtil.getExcelFromLocal(file, Stock.class);
                log.info("{}文件的数据量{}", file.getName(), stocks.size());
                for (Stock stock : stocks) {
                    stock.setDate(DateUtil.getDate(date));
                    String marketValue = stock.getTotalMarketValue();
                    if (StringUtil.isNotEmpty(marketValue) && marketValue.endsWith("万亿")) {
                        double newMarketValue = Double.valueOf(marketValue.replace("万亿", "")) * 10000;
                        marketValue = String.format("%.2f亿", newMarketValue);
                        stock.setTotalMarketValue(marketValue);
                    }
                    stockService.saveOrUpdate(stock);
                }
                FilesUtil.copy(file.getPath(), StringUtil.join(finishedFilePath, file.getName()));
                FilesUtil.delete(file);

                stockService.addDateValue(date);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("导入失败:" + file.getName());
            }
        }
    }
}
